<template>
  <el-dialog
    v-model="dialogVisible"
    title="设置映射关系"
    width="500px"
    @close="resetForm"
  >
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="模板" prop="itemIds">
        <el-select
          v-model="form.itemIds"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="4"
          placeholder="请选择"
          class="w-full"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.standardCode"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { message } from "@/utils/message";
import { setAdminTemplateHeadItemIds } from "@/api/adminTemplateHeadApi";
import { getAdminTemplateItems } from "@/api/adminTemplateApi";
import type { FormInstance, FormRules } from "element-plus";
interface RuleForm {
  itemIds: string[];
}
const emits = defineEmits(["refresh"]);
const dialogVisible = ref(false);
const loading = ref(false);
const form = ref({
  itemIds: []
});
const templateId = ref("");
// 基础校验规则
const rules = reactive<FormRules<RuleForm>>({
  itemIds: [
    {
      type: "array",
      required: true,
      message: "请选择模板",
      trigger: "change"
    }
  ]
});
const ruleFormRef = ref<FormInstance>();
// 重置表单
const resetForm = () => {
  templateId.value = "";
  ruleFormRef.value?.clearValidate();
  ruleFormRef.value?.resetFields();
};

const handleConfirm = () => {
  ruleFormRef.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true;
        const { message: text } = await setAdminTemplateHeadItemIds(
          templateId.value,
          form.value
        );
        emits("refresh");
        message(text || "更新成功", { type: "success" });
        dialogVisible.value = false;
      } catch (error) {
        console.log(error);
      } finally {
        loading.value = false;
      }
    }
  });
};
const open = (row: { id: string; itemIds: any }) => {
  if (row?.id) {
    templateId.value = row.id;
    form.value = {
      itemIds: row.itemIds
    };
  }
  dialogVisible.value = true;
};
const options = ref<any[]>([]);
const onSearch = async () => {
  try {
    const { data } = await getAdminTemplateItems();
    options.value = data;
  } catch (error) {
    message("获取数据失败", { type: "error" });
    console.log(error);
  }
};
onSearch();
defineExpose({
  open
});
</script>
